//
//  YuanXinWebView.m
//  YuanXinWebView
//
//  Created by 晏德智 on 16/7/27.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "YuanXinWebView.h"
#import <WebKit/WebKit.h>

@interface YuanXinWebView ()


@end

@implementation YuanXinWebView

@synthesize injectedJavaScript   =    _injectedJavaScript;

@synthesize onLoadingStart       =    _onLoadingStart;
@synthesize onLoadingFinish      =    _onLoadingFinish;
@synthesize onLoadingError       =    _onLoadingError;
@synthesize onShouldStartLoadWithRequest     = _onShouldStartLoadWithRequest;
@synthesize onProgress           =    _onProgress;

@synthesize automaticallyAdjustContentInsets = _automaticallyAdjustContentInsets;
@synthesize contentInset         =   _contentInset;
@synthesize sendCookies          =   _sendCookies;
@synthesize source               =   _source;
@synthesize progressStyle        =   _progressStyle;
@synthesize showProgress         =   _showProgress;

#pragma mark - constructor

static NSDictionary *colorStringDic = nil;
__attribute__((constructor))
static void initialize_colorStringDic() {
    colorStringDic = @{@"BLACK": [UIColor blackColor],
                       @"DARKGRAY": [UIColor darkGrayColor],
                       @"LIGHTGRAY": [UIColor lightGrayColor],
                       @"WHITE": [UIColor whiteColor],
                       @"GRAY": [UIColor grayColor],
                       @"RED": [UIColor redColor],
                       @"ORANGE": [UIColor orangeColor],
                       @"YELLOW": [UIColor yellowColor],
                       @"GREEN": [UIColor greenColor],
                       @"BLUE": [UIColor blueColor],
                       @"CYAN": [UIColor cyanColor],
                       @"PURPLE": [UIColor purpleColor],
                       @"BROWN": [UIColor brownColor],
                       @"MAGENTA": [UIColor magentaColor],
                       @"CLEAR": [UIColor clearColor],
                       @"TRANSPARENT": [UIColor clearColor]};
}

__attribute__((destructor))
static void destroy_colorStringDic() {
    colorStringDic = nil;
}


RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder)

- (void)dealloc {
    self.delegate = nil;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])) {
        super.backgroundColor = [UIColor clearColor];
        _sendCookies = YES;
        _automaticallyAdjustContentInsets = YES;
        _contentInset = UIEdgeInsetsZero;
    }
    return self;
}

/**
 清理缓存
 */
+ (void)clearWbCache {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes
        = [NSSet setWithArray:@[
                                WKWebsiteDataTypeDiskCache,
                                WKWebsiteDataTypeOfflineWebApplicationCache,
                                WKWebsiteDataTypeMemoryCache,
                                //WKWebsiteDataTypeLocalStorage,
                                //WKWebsiteDataTypeCookies,
                                //WKWebsiteDataTypeSessionStorage,
                                //WKWebsiteDataTypeIndexedDBDatabases,
                                //WKWebsiteDataTypeWebSQLDatabases
                                ]];
        //// All kinds of data
        //NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        //// Date from
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        //// Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            // Done
        }];
        
    } else {
        
        NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                                   NSUserDomainMask, YES)[0];
        NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]
                                objectForKey:@"CFBundleIdentifier"];
        NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
        NSString *webKitFolderInCaches = [NSString
                                          stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
        NSString *webKitFolderInCachesfs = [NSString
                                            stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
        
        NSError *error;
        /* iOS8.0 WebView Cache的存放路径 */
        [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
        [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
        
        /* iOS7.0 WebView Cache的存放路径 */
        [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
        
    }
}

- (void)loadRequest:(NSURLRequest *)request {
    if (request.URL && _sendCookies) {
        NSDictionary *cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
        if ([cookies objectForKey:@"Cookie"]) {
            NSMutableURLRequest *mutableRequest = request.mutableCopy;
            [mutableRequest addValue:cookies[@"Cookie"] forHTTPHeaderField:@"Cookie"];
            request = mutableRequest;
        }
    }
}

/**
 *  将消息推送到React
 *
 *  @param parames 参数
 *
 *  @return 是否推送成功
 */
- (BOOL)sendBridgeMessage:(NSString *)messageType body:(id)parames{
    
    BOOL result = NO;
    @try {
        if(self.onBridgeMessage){
            NSMutableDictionary<NSString *, id> *onBridgeMessageEvent = [[NSMutableDictionary alloc] initWithDictionary:@{
                                                                                                                          messageType:parames}];
            
            self.onBridgeMessage(onBridgeMessageEvent);
            result = YES;

        }
        
    } @catch (NSException *exception) {
        result = NO;
    } @finally {
        
    }
    return result;
}


/**
 *  React 将消息推送到webView
 *
 *  @param value 传入参数
 */
- (void)sendToBridge:(NSString *)value{

}

/**
 *  执行javascript 方法
 *
 *  @param script  javascript代码
 *  @param resolve <#resolve description#>
 *  @param reject  <#reject description#>
 */
- (void)evaluateScript:(NSString *)script resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject{

}

- (NSArray*)stringArrayJsonToArray:(NSString *)message
{
    return [NSJSONSerialization JSONObjectWithData:[message dataUsingEncoding:NSUTF8StringEncoding]
                                           options:NSJSONReadingAllowFragments
                                             error:nil];
}

#pragma mark - utils
// 颜色
#define Color_rgba(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define Color_rgb(r,g,b) Color_rgba(r, g, b, 1.0f)
// 16进制颜色值
#define DEFAULT_VOID_COLOR [UIColor blackColor]
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

// 颜色字符串转颜色值
+ (UIColor *)colorWithString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    UIColor *handledColor = nil;
    // #f5fcff
    if ([cString hasPrefix:@"#"]) {
        handledColor = [self colorWithHexString:cString];
    }
    // rgba(0, 0, 0, 0.8)
    else if ([cString hasPrefix:@"RGBA"]) {
        NSUInteger location = [cString rangeOfString:@"RGBA("].location;
        NSUInteger length = (cString.length-1)-(location+1);
        if (location != NSNotFound) {
            NSString *rgbaStr = [cString substringWithRange:NSMakeRange(location, length)];
            NSArray *rgbaArray = [rgbaStr componentsSeparatedByString:@","];
            if ([rgbaArray count] == 4) {
                handledColor = Color_rgba([rgbaArray[0] integerValue], [rgbaArray[1] integerValue], [rgbaArray[2] integerValue], [rgbaArray[3] floatValue]);
            }
        }
    }
    else if ([cString hasPrefix:@"RGB"]) {
        NSUInteger location = [cString rangeOfString:@"RGB("].location;
        NSUInteger length = (cString.length-1)-(location+1);
        if (location != NSNotFound) {
            NSString *rgbaStr = [cString substringWithRange:NSMakeRange(location, length)];
            NSArray *rgbaArray = [rgbaStr componentsSeparatedByString:@","];
            if ([rgbaArray count] >= 3) {
                handledColor = Color_rgba([rgbaArray[0] integerValue], [rgbaArray[1] integerValue], [rgbaArray[2] integerValue], 1.0f);
            }
        }
    }
    else {
        handledColor = colorStringDic[cString];
    }
    
    return handledColor;
}

@end

